import tw.forms
from tw.forms import FieldSet, ListMixin, SecureFormMixin

from pylons import session
from pylons import request

from cibynet.lib import utils


class SimpleForm(tw.forms.Form, SecureFormMixin):
  """Just a form as it should be. Let us use _method field with PUT and DELETE.
  Has:
    - a secret hidden field to avoid cross site request forgery.
    - an hidden field for the method
  """
  template = "cibynet.lib.twforms.templates.simple_form"
  
  def update_params(self, d):
    super(SimpleForm, self).update_params(d)
    if d.method in ['put', 'delete']:
      d.method_field = d.method.upper()
      d.method = 'post'
      
  def validate(self, params, *args, **kw):
    if '_method' in params:
      params.pop('_method')
    if '_ajax' in params:
      params.pop('_ajax')
    return super(SimpleForm, self).validate(params, *args, **kw)

  def session_secret_cb(self):
    """Return session-specific secret data string and some data.
    Both of them should stay constant per form per user.
    """
    secret = session.get('ssf') # ssf = secret secure form
    if not secret:
      session['ssf'] = secret = utils.get_random_string(16)
      session.save()
    identity = request.environ.get('repoze.who.identity', {})
    user_id = identity.get('repoze.who.userid', 0)
    return str(secret), str(user_id)
  

class ListFieldSet(FieldSet, ListMixin):
  """
  A fieldset that renders it's fields as an unordered list
  """
  template = "cibynet.lib.twforms.templates.div_fieldset"
